package com.mlz.mlzmall.ui.activity.act.personal.userLogin;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.Response;
import com.mlz.mlzmall.R;
import com.mlz.mlzmall.bean.UserBean;
import com.mlz.mlzmall.ui.activity.act.base.TopTitleView;
import com.mlz.mlzmall.ui.activity.act.personal.NetworkRequest.MyCenterUtils;
import com.mlz.mlzmall.ui.activity.act.personal.NetworkRequest.RequestUtils;
import com.mlz.mlzmall.ui.activity.act.personal.NetworkRequest.TimeUtil;
import com.mlz.mlzmall.ui.activity.act.personal.NetworkRequest.VolleyBaseActivity;
import com.mlz.mlzmall.ui.utils.mlz.ConfigInfo;
import com.mlz.mlzmall.ui.utils.mlz.URL;
import com.mlz.mlzmall.ui.utils.util.ACache;
import com.mlz.mlzmall.ui.utils.util.SharedUtils;
import com.mlz.mlzmall.ui.utils.vali.AbStrUtil;
import com.mlz.mlzmall.ui.utils.vali.UIUtils;

import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.Timer;
import java.util.TimerTask;


/**
 * 注册页面
 * Created by Administrator on 2016/5/18.
 */
public class RegistActivity extends VolleyBaseActivity implements View.OnClickListener {
    public static final String TGA = "RegistActivity";
    private UserBean userbean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.regist_activity);
        assignViews();
        setViewContent();
        setViewLinstener();
        getSession();
        userbean = new UserBean();

    }

    private TopTitleView registTopTitle;
    private EditText etPhoneNumber;
    private EditText etCode;
    private TextView tvGetCode;
    private Button btnNextStep;
    private TextView tvToLogin;

    /**
     * 初始话控件
     */
    private void assignViews() {
        registTopTitle = (TopTitleView) findViewById(R.id.regist_top_title);
        etPhoneNumber = (EditText) findViewById(R.id.et_phone_number);
        etCode = (EditText) findViewById(R.id.et_code);
        tvGetCode = (TextView) findViewById(R.id.tv_get_code);
        btnNextStep = (Button) findViewById(R.id.btn_next_step);
        tvToLogin = (TextView) findViewById(R.id.tv_to_login);
    }

    /**
     * 为控件设置内容
     */
    private void setViewContent() {
        registTopTitle.setLeftButtonContent(null, R.mipmap.pic_2_1_btn_back, null);
        registTopTitle.setTitleButtonContent("注册", null, null);
    }

    /**
     * 控件监听事件
     */
    private void setViewLinstener() {
        etPhoneNumber.setOnClickListener(this);
        etCode.setOnClickListener(this);
        tvGetCode.setOnClickListener(this);
        btnNextStep.setOnClickListener(this);
        tvToLogin.setOnClickListener(this);
        registTopTitle.setOnLeftButtonClickListener(new TopTitleView.OnLeftButtonClickListener() {
            @Override
            public void onLeftBtnClick(View button) {
                finish();
                RegistActivity.this.overridePendingTransition(R.anim.right_in, R.anim.right_out);
            }
        });
    }

    CountDownTimer messageTimer = new CountDownTimer(60000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            if (tvGetCode != null) {
                tvGetCode.setText("重新发送（" + (int) (millisUntilFinished / 1000) + "）");
            }
        }

        @Override
        public void onFinish() {
            if (tvGetCode != null) {
                tvGetCode.setText("重新获取验证码");
            }
        }
    };
    private String loginName, code;
    private String type = "regist";

    /**
     * 获取验证码
     */
    private void getMessageCode() {
        loginName = etPhoneNumber.getText().toString().trim();
        userbean.setAccout(loginName);
        Log.i("手机号", loginName);
        if (!AbStrUtil.isMobileNO(loginName)) {
            MyCenterUtils.ToastText("手机格式有误");
            return;
        }

        if (UIUtils.canSendMessage()) {
            UIUtils.saveTimeSendMessage();
            messageTimer.start();
            executeRequest(RequestUtils.getMLZRequestCode(mContext, loginName, type, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject jsonObject) {
                    try {
                        JSONObject json = new JSONObject(jsonObject.toString());
                        String msg = json.getString("msg");
                        MyCenterUtils.ToastText(msg);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }));

        } else {
            MyCenterUtils.ToastText("短信请求已发送，请耐心等待");
        }
    }

    public static String LOGINNAME = "LOGINNAME";
    public static String USERCODE = "USERCODE";

    private void getSession() {
        executeRequest(RequestUtils.getSession(mContext, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    JSONObject json = new JSONObject(s);
                    String data = json.getString("data");
                    JSONObject json1 = new JSONObject(data);
                    String sessionKey = json1.getString("sessionKey");
                    // 把 sessionKey 字符串保存到手机内部存储卡
                    ACache mCache = ACache.get(getApplication());
                    Log.i(TGA, "注册获取的session:" + data);
                    // 存放时间设定为1天,默认数量为1，更新会覆盖前面的值
                    if (data != null) {
                        mCache.put("sessionKeyTest", sessionKey, ACache.TIME_DAY);
                        Log.i(TGA, "取出session：" + ACache.get(getApplication()).getAsString("sessionKeyTest"));
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_get_code:
                getMessageCode();
                break;
            case R.id.btn_next_step:
                loginName = etPhoneNumber.getText().toString().trim();
                Log.i(TGA, "1111");
                code = etCode.getText().toString().trim();
                Log.i(TGA, loginName + "   " + code);
                if (loginName.length() == 0 || code.length() == 0) {
                    MyCenterUtils.ToastText("手机号和验证码不能为空");
                }
                executeRequest(RequestUtils.getMLZRegistCode(mContext, loginName, code, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        try {
                            Log.i(TGA, "1211" + jsonObject.toString());
                            JSONObject json = new JSONObject(jsonObject.toString());
                            int status = json.getInt("status");
                            Log.i(TGA, "1311");
                            if (0 == status) {//成功跳转到下一个页面
                                Log.i(TGA, "1411");
                                Intent intent = new Intent(RegistActivity.this, RegistTwoActivity.class);
                                intent.putExtra(LOGINNAME, loginName);
                                intent.putExtra(USERCODE, code);
                                startActivity(intent);
                            }
                            String msg = json.getString("msg");//不成功显示信息
                            if (0 != status) {
                                MyCenterUtils.ToastText(msg);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }));
                break;
            case R.id.tv_to_login:
                Intent intent = new Intent(RegistActivity.this, LoginActivity.class);
                enterAtivityNotFinish(intent);
                break;
        }
    }

}
